#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Can be called from remote system via SSH, for example as restricted command
# of a specific SSH key. It reads stdin for
# a) a header (specificing if its the configuration or status info)
# b) the real data as generated by livedump
#
# When the first line contains the string "status", the following lines
# are all treated as checkresult information. If the line contains the
# string "config", the following lines are treated as nagios configuration
# definitions. All chars after the config string in the subject are used
# to identfy the sending system. This is an ident of the system to support
# multiple sending systems.
#
# Configuration is written to etc/nagios/conf.d/remote-<ident>.cfg.
# The status info is sent in nagios state result file format and
# written to tmp/nagios/checkresults directory in a temporary file
# which is then processed by nagios.

import os
import sys
import tempfile

omd_root = os.environ.get('OMD_ROOT')

mode = None
first = True
content = ""

for line in sys.stdin:
    if first:
        if line.startswith("status"):
            mode = "status"
        elif line.startswith("config"):
            mode = "config"
            ident = line[6:].strip().replace("/", "_").replace(".", "_")
        first = False
    else:
        content += line

if mode == "config":
    open("%s/etc/nagios/conf.d/remote-%s.cfg" % (omd_root, ident), "w").write(content)

elif mode == "status":
    fd, path = tempfile.mkstemp('', 'c', "%s/tmp/nagios/checkresults" % omd_root)
    os.write(fd, content)
    os.close(fd)
    open(path + ".ok", "w")
else:
    sys.stderr.write("ERROR: Invalid mode\n")
    sys.exit(1)
